package com.hundsun.epay.autosimu.codegen.jfinal.trade;

import java.util.Set;
import java.util.TreeSet;

import com.hundsun.epay.autosimu.api.dom.java.FullyQualifiedJavaType;
import com.hundsun.epay.autosimu.api.dom.java.Method;
import com.hundsun.epay.autosimu.api.dom.java.TopLevelClass;
import com.hundsun.epay.autosimu.internal.ObligateInnerVariableName;

public class NotifyTradeGenerator extends JFinalAbstractTradeGenerator {

	@Override
	public void addTradeImplementsElements(TopLevelClass topClass) {
		Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
		Method method = getMethodShell();
		String line = "";
		if(Boolean.TRUE.equals(getIntrospectedTrade().getNotifySync())){
			//读取订单号，透传字段参数
			getAbstractRequestDataDrawer().addDrawRequestDataExpression(importedTypes, this, method.getBodyLines());
			importedTypes.add(new FullyQualifiedJavaType("com.hundsun.epay.simu.model.Orders"));
//			importedTypes.add(new FullyQualifiedJavaType("com.hundsun.epay.simu.service.OrderService"));
			importedTypes.add(new FullyQualifiedJavaType("com.alibaba.fastjson.JSONObject"));
			
			line = "";
			method.addBodyLine(line);
		}
		
		addDrawRequestDataFromDBExpression(importedTypes, method);
		
		method.addBodyLine("");
		
		//处理响应字段提取
		addDrawRespFieldExpression(importedTypes, method.getBodyLines());
		method.addBodyLine("");
		
		//处理响应替换
		assembleCheckSingleResp(method);
		
		//开始通知
		importedTypes.add(new FullyQualifiedJavaType("com.hundsun.epay.simu.common.notify.Notify"));
		importedTypes.add(new FullyQualifiedJavaType("net.dreamlu.event.EventKit"));
		importedTypes.add(new FullyQualifiedJavaType("com.hundsun.epay.simu.common.notify.event.NotifyEvent"));
		method.addBodyLine("");
		line = "Notify " + ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + " = new Notify();";
		method.addBodyLine(line);
		line = ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + ".setNotifyUrl(" + ObligateInnerVariableName.OBLIGATE_BACK_URL + ");";
		method.addBodyLine(line);
		line = ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + ".setNotifyCount(10);";
		method.addBodyLine(line);
		line = ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + ".setNotifyInterval(10000L);";
		method.addBodyLine(line);
		line = ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + ".setNotifyMsg(" + ObligateInnerVariableName.OBLIGATE_TEMPLATE_RESPMSG + ");";
		method.addBodyLine(line);
		line = "EventKit.post(new NotifyEvent(" + ObligateInnerVariableName.OBLIGATE_NOTIFY_OBJECT + "));";
		method.addBodyLine(line);
		
		//处理前台回调
		if(checkNeedRedirectFrontUrl()){
			method.addBodyLine("");
			line = "redirect(" + ObligateInnerVariableName.OBLIGATE_FRONT_URL + ");";
			method.addBodyLine(line);
		}
		
		topClass.addImportTypes(importedTypes);
		topClass.addMethod(method);
	}

}
